import 'package:flutter/material.dart';

class BackDemo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _BackDemoState();
  }
}

class _BackDemoState extends State<BackDemo> {
  DateTime _lastPressedAt; //上次点击时间

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text('返回键拦截的例子'),
      ),
      body: WillPopScope(
        child: Center(
          child: Text('1秒内连续按两次返回键退出',
            style: TextStyle(
              color: Colors.green,
            ),
            textScaleFactor: 2,
          ),
        ), 
        onWillPop: () async {
          if ((_lastPressedAt == null) || (DateTime.now().difference(_lastPressedAt) > Duration(seconds: 1))) {
            _lastPressedAt = DateTime.now();
            return false;
          } else {
            return true;
          }
        },
      ),
    );
  }
}